package com.android.wechat.msg.netty;


import com.android.wechat.msg.dao.TMsgDao;
import com.android.wechat.msg.entity.TMsgEntity;
import com.android.wechat.msg.service.TMsgService;
import com.android.wechat.msg.utils.ObjectToMessageProtocol;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


//处理业务的handler
@Component
@ChannelHandler.Sharable
@Slf4j
public class WebServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    @Autowired
    private TMsgDao tMsgDao;

    @Autowired
    private TMsgService tMsgService;

    private static WebServerHandler webServerHandler;

    @PostConstruct
    public void init(){
        webServerHandler = this;
    }

    //使用一个hashmap 管理
    public static Map<Long, Channel> userClients = new HashMap<Long,Channel>();

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     *  handlerAdded 表示连接建立，一旦连接，第一个被执行
     *  将当前channel 加入到  channelGroup
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送给其它在线的客户端
        /*
        该方法会将 channelGroup 中所有的channel 遍历，并发送 消息，
        我们不需要自己遍历
         */
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + " 加入聊天" + sdf.format(new java.util.Date()) + " \n");
        channelGroup.add(channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

//    /**
//     *
//     * @param ctx
//     * @param msg
//     * @throws Exception
//     */
//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
//
//        //接收到数据，并处理
//        TMsgEntity tMsgEntity = ObjectToMessageProtocol.MessageProtocolToObject(msg);
//
//
//        /**
//         * 将当前用户对应的channel加入缓存中
//         */
//        if(tMsgEntity != null){
//            userClients.put(tMsgEntity.getSendId(),ctx.channel());
//            if(tMsgEntity.getIsreceive()!= null && tMsgEntity.getIsreceive() == 1L && myServerHandler.tMsgDao.selectById(tMsgEntity.getMsgId()) != null){
//                //数据库中有数据，并且该数据已经被接收
//                myServerHandler.tMsgDao.insert(tMsgEntity);
//                return;
//            }
//
//            /**
//             * 创建响应协议包
//             */
//            MessageProtocol respMsg = new MessageProtocol();
//
//            boolean isReceive = false;
//            int count = 0;
//            while (count < 3 && !isReceive){
//                /**
//                 * 重试3次
//                 */
//                Channel receiveUser = userClients.get(tMsgEntity.getReceiveId());
//                if(receiveUser!=null && receiveUser.isActive()){
//                    //如果接收者处于活跃状态  发送数据
//                    isReceive = true;
//                    tMsgEntity.setSendTime(new Date());
//                    Long id = (long) myServerHandler.tMsgDao.insert(tMsgEntity);
//                    tMsgEntity.setMsgId(id);
//
//                    ObjectToMessageProtocol.ResultMsg result = ObjectToMessageProtocol.getResult(tMsgEntity);
//
//                    respMsg.setLen(result.length);
//                    respMsg.setContent(result.content);
//                    receiveUser.writeAndFlush(respMsg);
//                }
//                count++;
//            }
//            if(count == 3){
//                log.info("{} 号用户不在线，稍后再试",tMsgEntity.getReceiveId());
//            }
//        }
//    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {

    }
}
